package com.lanyam.travel.base.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanyam.travel.base.entity.GoodsInfo;
import com.lanyam.travel.base.entity.LineGoods;
import com.lanyam.travel.base.entity.ProductTicket;
import com.lanyam.travel.base.entity.ScenicHotel;
import com.lanyam.travel.base.entity.TicketType;
import com.lanyam.travel.base.entity.TravelLine;
import com.lanyam.travel.base.entity.vo.TravelLineVo;
import com.lanyam.travel.base.service.IGoodsInfoService;
import com.lanyam.travel.base.service.ILineGoodsService;
import com.lanyam.travel.base.service.IScenicHotelService;
import com.lanyam.travel.base.service.ITicketTypeService;
import com.lanyam.travel.base.service.ITravelLineService;
import com.lanyam.travel.base.utils.Constant;
import com.lanyam.travel.base.utils.FileUtil;
import com.lanyam.travel.base.utils.JSONResult;
import com.lanyam.travel.base.utils.JsonUtils;

@CrossOrigin
@RestController
@RequestMapping("line")
public class TravelLineController {

	@Autowired
	private ITravelLineService travelLineService;
	
	@Autowired
	private ITicketTypeService ticketTypeService;
	
	/**
	 * 添加旅游线路
	 * @param travelLine
	 * @return
	 * @RequestParam("files")List<MultipartFile> files
	 * ,MultipartFile file
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
//	@PostMapping("/addTravelLine")
	@RequestMapping(value = "/addTravelLine",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	public JSONResult addTravelLine(@RequestBody TravelLine travelLine)
	{
		String id = UUID.randomUUID().toString().replace("-", "");
		travelLine.setId(id);
		travelLine.setProductType(2);
		travelLine.setCreateTime(new Date());
		travelLineService.addTraveLine(travelLine);
		List<ProductTicket> ticketTypes = travelLine.getTicketTypes();
		if(null != ticketTypes && ticketTypes.size() > 0)
		{
			for (ProductTicket ticket : ticketTypes) {
				ticket.setId(UUID.randomUUID().toString().replace("-", ""));
				ticket.setProductId(id);
				ticketTypeService.createProductTicket(ticket);
			}	
		}
		return JSONResult.ok(travelLine);
	}
	
	/**
	 * 上传图片到旅游线路上
	 * @param lineId
	 * @param file
	 * @return
	 */
	@RequestMapping("/attachFileToLine")
	public JSONResult attachFileToLine(String lineId,@RequestParam(value = "files", required = false) MultipartFile[] files)
	{
		if(StringUtils.isEmpty(lineId) || null == files)
		{
			return JSONResult.errorMsg("旅游线路或文件不能为空。");
		}
		TravelLine line = travelLineService.getTravelLineById(lineId);
		String dbPathUri = "/img/scenic/"+lineId;
		String imgUri = FileUtil.uploadFile(files, dbPathUri);
		String oriImg = line.getImg();
		if(!StringUtils.isEmpty(oriImg))
		{
			oriImg += ";" + imgUri;
		}
		else
		{
			oriImg = imgUri;
		}
		line.setImg(oriImg);
		travelLineService.update(line);
		return JSONResult.ok(line);
	}
	
	/**
	 * 删除旅游线路上的图片
	 * @param lineId
	 * @param fileName
	 * @return
	 */
	@RequestMapping("/deleteImgInLine")
	public JSONResult deleteImgInLine(String lineId,String fileName)
	{
		if(StringUtils.isEmpty(lineId) || null == fileName)
		{
			return JSONResult.errorMsg("参数不全");
		}
		TravelLine travelLine = travelLineService.queryTravelLineById(lineId);
		String baseUri = Constant.FILE_UPLOAD_BASE_URI;
		File targetFile = new File(baseUri+fileName);
		if(targetFile.exists())
		{
			targetFile.delete();
		}
		String uri = fileName;
		String srcUri = travelLine.getImg();
		if(!StringUtils.isEmpty(srcUri))
		{
			String[] srcUris = srcUri.split(";");
			StringBuilder builder = new StringBuilder();
			for (int i = 0; i < srcUris.length; i++) {
				String path = srcUris[i];
				if(!uri.equals(path))
				{
					builder.append(path);
					builder.append(";");
				}
				
			}
			String img = builder.toString();
			if(img.length() > 0)
			{
				img = img.substring(0,img.length() - 1);
			}
			travelLine.setImg(img);
			travelLineService.update(travelLine);
		}
		
		
		return JSONResult.ok();
	}
	
	/**
	 * 给旅游线路增加图片
	 * @param lineId
	 * @param file
	 * @return
	 */
	@RequestMapping("/addImgToLine")
	public JSONResult addImgToLine(String lineId,@RequestParam(value = "file") MultipartFile file)
	{
		if(StringUtils.isEmpty(lineId))
		{
			return JSONResult.errorMsg("参数不全");
		}
		TravelLine travelLine = travelLineService.queryTravelLineById(lineId);
		String img = travelLine.getImg();
		int maxNum = 0;
		if(!StringUtils.isEmpty(img))
		{
			String[] imgUris = img.split(";");
			for (int j = 0; j < imgUris.length; j++) {
				String imgUri = imgUris[j];
				int index1 = imgUri.lastIndexOf("/");
				int index2 = imgUri.lastIndexOf(".");
				String name = imgUri.substring(index1, index2);
				try {
					int nameNum = Integer.parseInt(name);
					if(nameNum > maxNum)
					{
						maxNum = nameNum;
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		String dbPathUri = "/img/scenic/"+lineId;
		String fileName = (maxNum+1) + ".png"; 
		String imgUri = FileUtil.uploadFile(file, dbPathUri, fileName);
		travelLine.setImg(imgUri);
		travelLineService.update(travelLine);
		return JSONResult.ok(travelLine);
	}
	
	@PostMapping("/fileUpload")
	public JSONResult fileUpload(@RequestParam(value = "file", required = false) MultipartFile file)
	{
		System.out.println(file);
		MultipartFile originFile = file;
		String baseUri = Constant.FILE_UPLOAD_BASE_URI;
		String fileName = file.getOriginalFilename(); 
		String dbPathUri = "/img/pic";
		File targetFile = new File(baseUri+dbPathUri+"/"+fileName);
		System.out.println(targetFile.getAbsolutePath());
		 if(!targetFile.getParentFile().exists()) 
		 { 
			 targetFile.getParentFile().mkdirs(); 
		 }
		 try {
			 if(targetFile.exists()) 
			 {
				 targetFile.delete(); 
			 } 
			 originFile.transferTo(targetFile);
		 } catch (IllegalStateException | IOException e) { 
			 // TODO Auto-generated catch block
			 e.printStackTrace();
		 } 
		 return JSONResult.ok();
	}
	
	/**
	 * 获取旅游线路的详细信息,包含线路上的景点和酒店
	 * @param lineId
	 * @return
	 */
	@RequestMapping("/getTravelLineInfo")
	@ResponseBody
	public JSONResult getTravelLineInfo(String lineId)
	{
		TravelLine line = travelLineService.queryTravelLineInfo(lineId);
		return JSONResult.ok(line);
	}
	
	/**
	 * 删除某条旅游线路
	 * @param id 旅游线路id
	 * @return
	 */
	@RequestMapping("/deleteTravelLine")
	@ResponseBody
	public JSONResult deleteTravelLine(String id)
	{
		if(StringUtils.isEmpty(id))
		{
			return JSONResult.errorMsg("参数不全");
		}
		travelLineService.deleteById(id);
		String dbPathUri = "/img/scenic/"+id;
		//如果是更新图片，需要先删除原来存放的图片
		String baseUri = Constant.FILE_UPLOAD_BASE_URI;
		FileUtil.delFolder(baseUri+dbPathUri);
		return JSONResult.ok();
	}
	
	/**
	 * 更新旅游线路信息
	 * @param travelLine
	 * @return
	 */
	@RequestMapping("/updateTravelLine")
	@ResponseBody
	public JSONResult updateTravelLine(@RequestBody TravelLine travelLine)
	{
		travelLineService.update(travelLine);
		return JSONResult.ok();
	}
	/**
	 * 获取后端旅游线路分页数据
	 * reqMap中的key:name线路名称，region 0为国内1为国外,price价格
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@PostMapping(value = "/queryTravelLinePage",consumes = "application/json")
	public JSONResult queryTravelLinePage(int page,int pageSize,@RequestBody(required = false) Map<String, String> reqMap)
	{
		Page<TravelLine> ipage = travelLineService.queryTravelLinePage(page,pageSize,reqMap);
		return JSONResult.ok(ipage.getRecords());
	}
	
}
